<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Pagelass
 *
 * @author mavr
 */
ini_set('display_errors',1);
include_once  $_SERVER['DOCUMENT_ROOT']."/class/sqlclass.php";

class PageClass extends sqlclass{
    var $sql;
    var $table;

    function PageClass() {
        echo "создаем подключение к базе...   ";
        $this->sql = $this->sqlclass();
        if (!$this->sql) $this->error("fail");
        echo "ok<br>";
    }
    
    function checkAuth($id,$sessid,$group) {
        /*
         * функция проверяет авторизовыванность пользователя
         * 1- норм, 0 - не авторизован
         */

        $query = "select groupid from `users` where `id` = '$id' and `sid` = '$sessid'";

        if (!$this->sql->sql_query($query))
        {
            $err = $this->sql->sql_error();
            return ("-1");
        }
        if ($this->sql->sql_numrows() !== 1) return 0;
        
        $req = $this->sql->sql_fetchrow();
        if ($req['0'] == $group) return 1;
        return 0;

    }

    function RootLog ($string)
    {
        $file = fopen ("../users/root/log/enter-log.txt",'a');
        fputs ($file,$string);
        fclose($file);
    }

    function error ($mess)
    {
        die ($mess);
    }

    function prsPhone ($phone)
    {
        $arrphone = explode ('|',$phone);
        if (isset ($arrphone[1]))
            $phone = "+".$arrphone[0]." (".$arrphone[1].") " ;
        else
            return $arrphone[0];
        if (isset ($arrphone[2]))
            $phone .= $arrphone[2];
        return $phone;
    }

    function sendMail ($to,$subj,$messa)
    {
        $file = $_SERVER['DOCUMENT_ROOT']."/Mailconfig.xml";
        $xmlfile = file_get_contents($file);
        $xml = new SimpleXMLElement($xmlfile);
        $who = $xml->MailConfig->WhoFrom;
        $fromMail = $xml->MailConfig->MailFrom;
        $form = "Content-type: text/plain; charset=\"windows-1251\"";
        $from = "From: ".$who." <".$fromMail.">";
        $subject = $subj;

        if (mail($to, $subject, $messa,$from)) return true;
        else return false;
    }

    /////////////////////////////////////////////////////////////////
//      Функция подстановки шаблонов для почтового робота      //
/////////////////////////////////////////////////////////////////
// 1. Все аргументы должны быть заполнены. Если аргумент не нужен
//   или неизвестен в данном случае, его надо объявить как пустую
//   строку.
// 2. $action может принимать целые значения от 1 до 4.
//   1-Автоматическое сообщение «Вопрос-ответ»
//   2-Ночной автоответчик для «Вопрос-ответ»
//   3-Сообщение об успешной регистрации
//   4-Сообщение о необходимости указать дополнительную информацию.

function mail_bot($username, $link, $user_mailbox, 
                      $user_order, $necessary_info,
                      $account_manager_name,
                      $account_manager_details, $action)
    {
        $query="SELECT `end_time` FROM `mailrobot` WHERE `act`='".$action."' and `active`=1";
        if (!$this->sql->sql_query($query)) {
            $err = $this->sql->sql_error();
            die ("internal_error");
        }
        $timer_end_time = $this->sql->sql_fetchrow();
        $timer_end_time = $timer_end_time[0];
        $site_adress = $_SERVER['SERVER_NAME'];
        $patrn = array ("/(~username~)/",
                        "/(~link~)/",
                        "/(~user_mailbox~)/",
                        "/(~user_new_order~)/",
                        "/(~necessary_info~)/",
                        "/(~account_manager_name~)/",
                        "/(~account_manager_details~)/",
                        "/(~site_adress~)/",
                        "/(~timer_end_time~)/");
        $right = array ($username, $link, $user_mailbox, 
                      $user_order, $necessary_info,
                      $account_manager_name,
                      $account_manager_details,
                      $site_adress,
                      $timer_end_time);

        $query="SELECT `text` FROM `mailrobot` WHERE `act`='".$action."' and `active`='1'";

        if (!$this->sql->sql_query($query)) {
            $err = $this->sql->sql_error();
            die ("internal_error");
        }

        $text = $this->sql->sql_fetchrow();
        //$text = nl2br($text[0]);
        $text = $text[0];
        //$text = preg_replace ("/(<br />)/","\n",$text);

        $result = preg_replace ($patrn,$right,$text);

        return $result;
    }

}

function translitIt($str)
{
    $tr = array(
        "А"=>"a","Б"=>"b","В"=>"v","Г"=>"g",
        "Д"=>"d","Е"=>"e","Ж"=>"j","З"=>"z","И"=>"i",
        "Й"=>"y","К"=>"k","Л"=>"l","М"=>"m","Н"=>"n",
        "О"=>"o","П"=>"p","Р"=>"r","С"=>"s","Т"=>"t",
        "У"=>"u","Ф"=>"f","Х"=>"h","Ц"=>"ts","Ч"=>"ch",
        "Ш"=>"sh","Щ"=>"sch","Ъ"=>"","Ы"=>"yi","Ь"=>"",
        "Э"=>"e","Ю"=>"yu","Я"=>"ya","а"=>"a","б"=>"b",
        "в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"j",
        "з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l",
        "м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
        "с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
        "ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"y",
        "ы"=>"yi","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya",
        " "=> "_", "."=> "", "/"=> "_"
    );
    return strtr($str,$tr);
}

function generate_password($number = 8)

  {

    $arr = array('a','b','c','d','e','f',

                 'g','h','i','j','k','l',

                 'm','n','o','p','r','s',

                 't','u','v','x','y','z',

                 'A','B','C','D','E','F',

                 'G','H','I','J','K','L',

                 'M','N','O','P','R','S',

                 'T','U','V','X','Y','Z',

                 '1','2','3','4','5','6',

                 '7','8','9','0');

    // Генерируем пароль

    $pass = "";

    for($i = 0; $i < $number; $i++)

    {

      // Вычисляем случайный индекс массива

      $index = rand(0, count($arr) - 1);

      $pass .= $arr[$index];

    }

    return $pass;

  }
?>
